import argparse
import json
import os
from dora import Node
from mofa.kernel.utils.log import write_agent_log
from mofa.kernel.utils.util import load_agent_config, create_agent_output
from mofa.run.run_agent import run_dspy_agent, run_crewai_agent, run_dspy_or_crewai_agent
from mofa.utils.files.read import read_yaml
import pyarrow as pa
import os
import glob
from mofa.utils.files.dir import get_relative_path
from mofa.utils.log.agent import record_agent_prompt_log, record_agent_result_log
import tkinter as tk
from tkinter import messagebox, scrolledtext

def show_long_message(title, message):
    #return
    root = tk.Tk()
    root.title(title)
    
    # 创建滚动文本框
    text_area = scrolledtext.ScrolledText(root, wrap=tk.WORD, width=800, height=200)
    text_area.pack(padx=10, pady=10)
    text_area.insert(tk.END, message)
    text_area.config(state=tk.DISABLED)  # 设置为只读
    
    # 创建关闭按钮
    button = tk.Button(root, text="Close", command=root.destroy)
    button.pack(pady=10)
    
    root.mainloop()
RUNNER_CI = True if os.getenv("CI") == "true" else False

def main():
    # Handle dynamic nodes, ask for the name of the node in the dataflow, and the same values as the ENV variables.
    parser = argparse.ArgumentParser(description="Analysis Agent")

    parser.add_argument(
        "--name",
        type=str,
        required=False,
        help="The name of the node in the dataflow.",
        default="arrow-assert",
    )
    parser.add_argument(
        "--task",
        type=str,
        required=False,
        help="Tasks required for the Reasoner agent.",
        default="Paris Olympics",
    )

    args = parser.parse_args()
    task = os.getenv("TASK", args.task)

    node = Node()  # provide the name to connect to the dataflow if dynamic node

    for event in node:
        if event["type"] == "INPUT" and event['id'] in ['task','data','reasoner_task']:
            problems = event["value"][0].as_py()
            code = event["value"][1].as_py()
            
            if problems == "finish code":
                source_code = event["value"][2].as_py()
                yaml_file_path = get_relative_path(current_file=__file__, sibling_directory_name='configs',
                                                target_file_name='code_small_fix_agent.yml')
                inputs = load_agent_config(yaml_file_path)
                inputs['task'] = f"{code}"
                record_agent_prompt_log(agent_config=inputs, config_file_path=yaml_file_path, log_key_name='Agent Prompt')
                show_long_message("Code Fix", f"source code: {source_code} \n code: {code}")
                agent_result = run_dspy_or_crewai_agent(agent_config=inputs)
                show_long_message("Code Fix", f"result: {agent_result}")
                record_agent_result_log(agent_config=inputs,
                                        agent_result={inputs.get('log_step_name', "Step_one"): agent_result})
                node.send_output("fix_code", pa.array([agent_result]), event['metadata'])
            else:
                yaml_file_path = get_relative_path(current_file=__file__, sibling_directory_name='configs',
                                                target_file_name='code_fix_agent.yml')
                inputs = load_agent_config(yaml_file_path)
                inputs['task'] = f"'code':{code},'problems':{problems}"
                record_agent_prompt_log(agent_config=inputs, config_file_path=yaml_file_path, log_key_name='Agent Prompt')
                agent_result = run_dspy_or_crewai_agent(agent_config=inputs)
                results = {}
                record_agent_result_log(agent_config=inputs,
                                        agent_result={inputs.get('log_step_name', "Step_one"): agent_result})
                node.send_output("fix_code", pa.array([agent_result]), event['metadata'])

if __name__ == "__main__":
    main()